//
//  ClubGameDetailInfoViewController.swift
//  77Club
//
//  Created by Apple on 2024/9/3.
//

import UIKit
import JXSegmentedView
import ZLPhotoBrowser

private let headerID    = "ClubGameDetailHeaderView"
private let commitHeaderID    = "ClubGameDetailCommitHeaderView"

class ClubGameDetailInfoViewController: ClubBaseViewController, RaeAnimationProtocol {

    private var topView = ClubGameDetailTopView()
    private var bottomView = ClubGameDetailBottomView()
    private var sectionTitles = ["全部影像","游戏简介","平台价格","玩家评论"]
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubGameDetailGamePicCell.self,ClubGameDetailGameInfoCell.self,ClubGameDetailPriceCell.self,ClubGameDetailCommitCell.self,ClubGameDetailEmptyCommitCell.self)
        tableView.register(ClubGameDetailHeaderView.self, forHeaderFooterViewReuseIdentifier: headerID)
        tableView.register(ClubGameDetailCommitHeaderView.self, forHeaderFooterViewReuseIdentifier: commitHeaderID)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 200.0.Scale
//        tableView.sectionFooterHeight = 0
//        tableView.tableFooterView = UIView()
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: -1, right: 0)
        return tableView
    }()
    private var releaseButton = c_make_ex(UIButton.self)
        .image("GameDetail_yuyue").end()
    //release状态 1.预约 2.已预约 3.下载 4.打开
    private var releaseType = 1
    private var pageIndex = 1
    //是否有平台价格
    private var isPrice = false
    private var sortby = "1"
    private var commitCount = 0
    
    var topModel: ClubGameDetailModel? {
        didSet{
            guard let md = topModel else { return }
            topView.topModel = md
            if md.status == "2" {
                releaseButton.setImage("GameDetail_stop".toImage, for: .normal)
            }else{
                if md.is_shangjia {
                    //游戏类型1.手游 2.h5 3.页游
                    if md.system_type == 1 {
                        releaseType = 3
                        releaseButton.setImage("GameDetail_download".toImage, for: .normal)
                    }else{
                        releaseType = 4
                        releaseButton.setImage("GameDetail_open".toImage, for: .normal)
                    }
                }else{
                    if md.is_yuyue == 1 {
                        releaseType = 2
                        releaseButton.setImage("GameDetail_yuyued".toImage, for: .normal)
                    }else{
                        releaseType = 1
                        releaseButton.setImage("GameDetail_yuyue".toImage, for: .normal)
                    }
                }
            }
        }
    }
    
    var gameId: String = "" {
        didSet{
            self.topView.gameId = gameId
            loadData()
        }
    }
    
    private var detailModel: ClubGameDetailInfoModel = ClubGameDetailInfoModel()
    private var commentList:[ClubGameDetailCommentListModel] = []
    private var actives:[ClubGameCommunityNewsModel] = []
    
    // 当页面即将消失时，确保视频停止播放
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        NotificationCenter.default.post(name: .stopAudioPlayer, object: nil)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        tableView.reloadData()
        NotificationCenter.default.post(name: .inPlayAudioVC, object: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .clear
        
        view.subviews{
            tableView
            bottomView
        }
        
        tableView.leading(0).trailing(0).bottom(.tabBar_height).top(0)
        bottomView.leading(0).trailing(0).bottom(0).height(.tabBar_height)
        
        topView.frame = CGRect(x: 0, y: 0, width: .screenWidth, height: 281.0.Scale)
        tableView.tableHeaderView = topView
        
        tableView.refresh_pull {
            self.loadNewData()
        }
        
        topView.toInfoDetailBlock = {
            self.toIntroVC()
        }
        
        bottomView.clickCommitBlock = {
            self.toCommiteVC()
        }

        self.view.addSubview(releaseButton)
        releaseButton.addTarget(self, action: #selector(clickReleaseButton), for: .touchUpInside)
        let panGesture = UIPanGestureRecognizer(target: self, action:#selector(dragAction(gesture:)))
        releaseButton.addGestureRecognizer(panGesture)
        releaseButton.snp.makeConstraints { make in
            make.right.equalTo(0)
            make.width.equalTo(88.0.Scale)
            make.height.equalTo(80.0.Scale)
            make.bottom.equalTo(-CGFloat.tabBar_height)
        }
        
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
            tableView.insetsContentViewsToSafeArea = false
        }
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }

        tableView.contentInset = .zero
        tableView.scrollIndicatorInsets = .zero
        
        NotificationCenter.default.addObserver(self, selector: #selector(updateCommitData), name: .updateDetailCommitData, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(updateTopModel), name: .updateGameInfoAttentionState, object: nil)
    }
    
    @objc func updateTopModel(_ noti: Notification){
        if let isAttention = noti.userInfo?["isAttention"] as? Bool {
            topModel?.shoucang = isAttention ? 1 : 0
            var follow = Int(topModel?.follow ?? "0") ?? 0
            if isAttention {
                follow += 1
            }else{
                follow -= 1
            }
            topModel?.follow = "\(follow)"
        }
    }
    
    @objc private func updateCommitData(){
        self.loadNewCommitData()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

//MARK: - UITableViewDelegate, UITableViewDataSource
extension ClubGameDetailInfoViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        sectionTitles.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if section == 0 || section == 1 {
            return 1
        }else if section == 2 {
            if isPrice {
                return 1
            }else{
                if self.detailModel.commentList.count == 0 {
                    return 1
                }else{
                    return self.detailModel.commentList.count
                }
            }
        }else{
            if self.detailModel.commentList.count == 0 {
                return 1
            }else{
                return self.detailModel.commentList.count
            }
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClubGameDetailGamePicCell", for: indexPath) as! ClubGameDetailGamePicCell
            cell.imageModel = self.detailModel
            cell.didSelectVideo = { url in
                self.selectVideo(url: url)
            }
            cell.didSelectImage = { index,images in
                self.selectImage(index: index, images: images)
            }
            cell.updateTableviewUI = { type in
                self.detailModel.picture?.cateType = type
                tableView.reloadData()
            }
            return cell
        }else if indexPath.section == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClubGameDetailGameInfoCell", for: indexPath) as! ClubGameDetailGameInfoCell
            cell.model = self.detailModel
            cell.toIntroVCBlock = {
                self.toIntroVC()
            }
            cell.jumpToDetail = { md in
                if md.uid == "0" {
                    //官方
                    let detailVC = ClubForumDetailViewController()
                    detailVC.newId = md.id
                    self.navigationController?.pushViewController(detailVC, animated: true)
                }else{
                    let detailVC = ClubGameForumDetailViewController()
                    detailVC.postID = md.id
                    detailVC.pid = self.gameId
                    detailVC.gameModel = self.topModel
                    self.navigationController?.pushViewController(detailVC, animated: true)
                }
                
            }
            return cell
        }else if indexPath.section == 2 {

            if isPrice {
                let cell = tableView.dequeueReusableCell(withIdentifier: "ClubGameDetailPriceCell", for: indexPath) as! ClubGameDetailPriceCell
                cell.models = self.detailModel.scrapys?.prices
                return cell
            }else {
                
                if self.detailModel.commentList.count == 0 {
                    let cell = tableView.dequeueReusableCell(withIdentifier: "ClubGameDetailEmptyCommitCell", for: indexPath) as! ClubGameDetailEmptyCommitCell
                    cell.starBlock = {
                        self.toCommiteVC()
                    }
                    return cell
                }else{
                    let cell = tableView.dequeueReusableCell(withIdentifier: "ClubGameDetailCommitCell", for: indexPath) as! ClubGameDetailCommitCell
                    cell.isWhite = true
                    cell.model = self.detailModel.commentList[indexPath.row]
                    cell.didSelectImage = { index,images in
                        self.selectImage(index: index, images: images)
                    }
                    cell.clickLikeBlock = { id in
                        self.likeCommit(commitID: id)
                    }
                    cell.showMoreView = { model in
                        self.commitShare(model: model)
                    }
                    cell.userInfoVC = { uid in
                        self.toUserInfoVC(uid: uid)
                    }
                    return cell
                }
            }
            
        }else{
            
            if self.detailModel.commentList.count == 0 {
                let cell = tableView.dequeueReusableCell(withIdentifier: "ClubGameDetailEmptyCommitCell", for: indexPath) as! ClubGameDetailEmptyCommitCell
                cell.starBlock = {
                    self.toCommiteVC()
                }
                return cell
            }else{
                let cell = tableView.dequeueReusableCell(withIdentifier: "ClubGameDetailCommitCell", for: indexPath) as! ClubGameDetailCommitCell
                cell.isWhite = true
                cell.model = self.detailModel.commentList[indexPath.row]
                cell.didSelectImage = { index,images in
                    self.selectImage(index: index, images: images)
                }
                cell.clickLikeBlock = { id in
                    self.likeCommit(commitID: id)
                }
                cell.showMoreView = { model in
                    self.commitShare(model: model)
                }
                cell.userInfoVC = { uid in
                    self.toUserInfoVC(uid: uid)
                }
                return cell
            }
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if (!isPrice && indexPath.section == 2) || indexPath.section == 3 {
            if self.detailModel.commentList.count == 0 {
                return
            }
            let model = self.detailModel.commentList[indexPath.row]
            let detailVC = ClubGameDetailCommitDetailVC()
            detailVC.gameID = gameId
            detailVC.gid = model.id
            detailVC.updateDataBlock = {
                self.loadData()
            }
            self.navigationController?.pushViewController(detailVC, animated: true)
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.section == 2 {
            
            if isPrice {
                let arr = self.detailModel.scrapys?.prices
                let height = Double(arr?.count ?? 0) * 38.0.Scale + 10.0.Scale
                return height
            }else {
                if self.detailModel.commentList.count == 0 {
                    return 190.0.Scale
                }else{
                    return calCommitCellHight(row: indexPath.row)
                }
            }
        }else if indexPath.section == 3 {
            
            if self.detailModel.commentList.count == 0 {
                return 190.0.Scale
            }else{
                return calCommitCellHight(row: indexPath.row)
            }
        }
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let titleStr = sectionTitles[section]
        if titleStr == "玩家评论"{
            if self.detailModel.commentList.count == 0 {
                return nil
            }
            let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: commitHeaderID) as! ClubGameDetailCommitHeaderView
            header.sortBy = self.sortby
            header.updateDataBlock = { type in
                self.sortby = type
                self.loadNewCommitData()
            }
            header.commitBlock = {
                self.toCommiteVC()
            }
            return header
        }else{
            let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerID) as! ClubGameDetailHeaderView
            header.titleStr = sectionTitles[section]
            header.didAllButton = {
                self.toIntroVC()
            }
            return header
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        let titleStr = sectionTitles[section]
        if titleStr == "玩家评论"{
            if self.detailModel.commentList.count == 0 {
                return 0
            }
            return 100.0.Scale
        }else{
            return 35.0.Scale
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude // 尽可能小的高度
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }

    
    private func calCommitCellHight(row: Int) -> CGFloat {
        
        var height = 12.0.Scale + 75.0.Scale + 77.0.Scale
        let model = self.detailModel.commentList[row]
        let contentLabH = calculateTextHeight(text: model.content, font: 15.font_medium!, width: CGFloat.screenWidth - 48.0.Scale, maxLines: 3)
        height += contentLabH
        if model.images.count > 0 {
            height += 107.0.Scale + 12.0.Scale
        }
        if model.son_list.count > 0 {
            let son_m = model.son_list[model.son_list.count - 1]
            let commitStr = son_m.user_name + "：" + son_m.content
            let commitLabH = commitStr.calculateTextHeight(font: 13.font_medium!, width: CGFloat.screenWidth - 72.0.Scale)
            if commitLabH > 20 {
                height += 37.0 + 16.0.Scale
            }else{
                height += 19.0 + 16.0.Scale
            }
        }
        
        return height
    }
    
    func calculateTextHeight(text: String, font: UIFont, width: CGFloat, maxLines: Int) -> CGFloat {
        // 创建一个 NSTextStorage 用于文本计算
        let textStorage = NSTextStorage(string: text)
        let textContainer = NSTextContainer(size: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude))
        textContainer.lineBreakMode = .byTruncatingTail
        textContainer.maximumNumberOfLines = maxLines
        let layoutManager = NSLayoutManager()
            
        layoutManager.addTextContainer(textContainer)
        textStorage.addLayoutManager(layoutManager)
        textStorage.addAttribute(.font, value: font, range: NSRange(location: 0, length: text.count))
            
        // 计算文本的高度
        layoutManager.glyphRange(for: textContainer)
        let usedRect = layoutManager.usedRect(for: textContainer)
        
        return ceil(usedRect.height) // 向上取整
    }
}

//MARK: action
extension ClubGameDetailInfoViewController {
    
    private func selectImage(index: Int, images: [String]) {
        
        var datas: [Any] = []
        for a in images {
            datas.append(URL(string: a)!)
        }
        let vc = ZLImagePreviewController(datas: datas, index: index, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .image
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
    
    private func selectVideo(url: String) {
        
        let vc = ZLImagePreviewController(datas: [URL(string: url)!], index: 0, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .video
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
    
    @objc private func dragAction(gesture: UIPanGestureRecognizer) {
        
        // 移动状态
        let moveState = gesture.state
        switch moveState {
        case .began:
            break
        case .changed:
            // floatBtn 获取移动轨迹
            let point = gesture.translation(in: self.view)
            self.releaseButton.center = CGPoint(x: self.releaseButton.center.x + point.x, y: self.releaseButton.center.y + point.y)
            break
        case .ended:
            // floatBtn 移动结束吸边
            let point = gesture.translation(in: self.view)
            var newPoint = CGPoint(x: self.releaseButton.center.x +  point.x, y: self.releaseButton.center.y + point.y)
            if newPoint.x < .screenWidth / 2.0 {
                newPoint.x = self.releaseButton.bounds.width/2 + 17.0.Scale
            } else {
                newPoint.x = .screenWidth - self.releaseButton.bounds.width/2 - 17.0.Scale
            }
            if newPoint.y <= self.releaseButton.bounds.height/2 + 17.0.Scale + .navi_height{
                newPoint.y = self.releaseButton.bounds.height/2 + 17.0.Scale + .navi_height
            } else if newPoint.y >= self.view.bounds.height - self.releaseButton.bounds.height/2 - 17.0.Scale {
                newPoint.y = self.view.bounds.height - self.releaseButton.bounds.height/2 - 17.0.Scale
            }
            // 0.5秒 吸边动画
            UIView.animate(withDuration: 0.5) {
                self.releaseButton.center = newPoint
            }
            break
        default:
            break
        }
        // 重置 panGesture
        gesture.setTranslation(.zero, in: self.view)
    }
    
    @objc private func clickReleaseButton() {
        //release状态 1.预约 2.已预约 3.下载 4.打开
        if releaseType == 1 {
            guard let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 else {
                self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
                return
            }
            Task{
                let res = await self.network.request(.addAppointment(gid: gameId),isShowError: false)
                if res.isSuccess {
                    self.releaseType = 2
                    self.releaseButton.setImage("GameDetail_yuyued".toImage, for: .normal)
                }
            }
        }else if releaseType == 3 {
            //跳转至appstore
            guard let appUrl = topModel?.ios, appUrl.count > 0 else {
                if let appStoreURL = URL(string: "itms-apps://itunes.apple.com") {
                    if UIApplication.shared.canOpenURL(appStoreURL) {
                        UIApplication.shared.open(appStoreURL, options: [:], completionHandler: nil)
                    }
                }
                return
            }
            if let url = URL(string: appUrl) {
                if UIApplication.shared.canOpenURL(url) {
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                }
            }
        }else if releaseType == 4 {
            //跳转到网页
            guard let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 else { return }
            let urlString = RaeRequestParameterConfig.shared.baseUrlStr + "ct=h5login&gid=" + self.gameId + "&uid=" + uid + "&type=1&t=" + RaeRequestParameterConfig.shared.getTStr() + "&sign=" + RaeRequestParameterConfig.shared.encrySign()
            let webView = ClubWebViewController()
            webView.urlString = urlString
            webView.titleName = "网页游戏"
            webView.ishiddenNav = true
//            webView.JSData = dict
            self.navigationController?.pushViewController(webView, animated: true)
        }
    }
    
    private func toUserInfoVC(uid: String){
        
        if uid.count > 0 {
            if let user_id = UserDefaultsManager.getString(forKey: .uid), user_id.count > 0, user_id == uid {
                let otherVC = ClubMineInfoViewController()
                self.navigationController?.pushViewController(otherVC, animated: true)
            }else{
                let otherVC = ClubOtherInfoViewController()
                otherVC.uid = uid
                otherVC.updateBlock = {
                    self.loadNewData()
                }
                self.navigationController?.pushViewController(otherVC, animated: true)
            }
        }        
    }
    
    private func toIntroVC(){
//        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            let introVC = ClubIntroDetailViewController()
            introVC.model = self.detailModel
        introVC.infoModel = self.topModel
            self.navigationController?.pushViewController(introVC, animated: true)
//        }else{
//            self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
//        }
    }
    
    private func toCommiteVC(){
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            let commitVC = ClubGamesCommitViewController()
            commitVC.gameId = self.gameId
            commitVC.topModel = self.topModel
            commitVC.updateDataBlock = {
                self.loadNewCommitData()
            }
            self.present(commitVC, animated: true)
        }else{
            self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }
    }
    
    private func commitShare(model: ClubGameDetailCommentListModel){
        let moreView = ClubGameMoreView()
        moreView.uid_des = model.uid_des
        moreView.reportBlock = {
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                let reportVC = ClubReportViewController()
                reportVC.dynamicID = model.id
                reportVC.type = "2"
                self.present(reportVC, animated: true)
            }else{
                //登录
                self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
            }
        }
        moreView.delBlock = {
            Task{
                let res = await self.network.request(.delCommit(commitID: model.id))
                if res.isSuccess {
                    "删除成功".toast_success
                    self.loadNewCommitData()
                }
            }
        }

        self.entryAnimate.animation(show: moreView)
    }
}


//MARK: data
extension ClubGameDetailInfoViewController {

    private func loadData(){
        
        ToastUtil.show()
        let netGroup = DispatchGroup()
        let workingQueue = DispatchQueue(label: "GameDetail")
        
        netGroup.enter()
        workingQueue.async {
            Task{
                let res = await self.network.requestMore(.gameDetailInfo(gameID: self.gameId), type: ClubGameDetailInfoModel.self)
                if let model = res.model, res.isSuccess {
                    self.detailModel = model
                    netGroup.leave()
                }
            }
        }
        netGroup.enter()
        workingQueue.async {
            Task{
                let res = await self.network.requestMore(.commitList(gameId: self.gameId, page: self.pageIndex, sortby: self.sortby),type: ClubGameDetailCommentDataModel.self)
                if res.isSuccess, let model = res.model {
                    self.commentList = model.data
                    self.commitCount = model.count
                    netGroup.leave()
                }
            }
        }
        netGroup.enter()
        workingQueue.async {
            Task {
                ToastUtil.show()
                let res = await self.network.request(.communityTop(communityID: self.gameId),type: ClubGameCommunityModel.self)
                if res.isSuccess, let model = res.model {
                    self.actives = model.news
                    netGroup.leave()
                }
            }
        }
        netGroup.notify(queue: workingQueue) {
            DispatchQueue.main.asyncAfter(deadline: .now()) {
                ToastUtil.dismiss()
                self.tableView.refresh_end()
                self.detailModel.commentList = self.commentList
                self.detailModel.actives = self.actives
                self.topView.detailModel = self.detailModel
                self.bottomView.number = self.commitCount
                if let prices = self.detailModel.scrapys?.prices, prices.count > 0 {
                    self.isPrice = true
                    self.sectionTitles = ["全部影像","游戏简介","平台价格","玩家评论"]
                }else{
                    self.isPrice = false
                    self.sectionTitles = ["全部影像","游戏简介","玩家评论"]
                }
                if self.commentList.count > 0 {
                    self.tableView.refresh_loadMore {
                        self.loadMoreData()
                    }
                }
                self.tableView.reloadData()
            }
            
        }
    }
 
    private func loadMoreData() {
        pageIndex += 1
        Task{
            let res = await self.network.request(.commitList(gameId: self.gameId, page: self.pageIndex, sortby: self.sortby),type: ClubGameDetailCommentListModel.self)
            if res.isSuccess, let models = res.models {
                self.tableView.refresh_end()
                self.commentList.append(contentsOf: models)
                self.detailModel.commentList = self.commentList
                self.tableView.refresh_end(!(models.count > 0))
                self.tableView.reloadData()
            }
        }
    }
    
    private func loadNewCommitData() {

        Task{
            let res = await self.network.request(.commitList(gameId: self.gameId, page: 1, sortby: self.sortby),type: ClubGameDetailCommentListModel.self)
            ToastUtil.dismiss()
            if res.isSuccess, let models = res.models {
                self.tableView.refresh_end()
                self.commentList = models
                self.detailModel.commentList = self.commentList
                self.tableView.reloadData()
            }
        }
    }
    
    private func loadNewData() {
        pageIndex = 1
        loadData()
    }
    
    private func likeCommit(commitID: String){
        
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            Task{
                ToastUtil.show()
                let res = await self.network.request(.likeGameCommit(commitID: commitID))
                if res.isSuccess {
                    self.loadNewCommitData()
                }
            }
        }else{
            self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }
    }
}

extension ClubGameDetailInfoViewController:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}
